//
//  WebViewController.m
//  YYZB
//
//  Created by 顾悦 on 16/3/21.
//
//

#import "WebViewController.h"

#import "ThemeColor.h"

#import "WebViewManager.h"
#import "WebViewController.h"
#import "WebService.h"

#import "LoadingView.h"

#import "AppStorage.h"
#import "AppConfiguration.h"
static NSString * webViewMessageNameReload = @"reload";
static NSString * webViewMessageNameGetSessionInfo = @"getSessionInfo";
static NSString * webViewMessageNamePushView = @"pushView";
static NSString * webViewMessageNameSetTitle = @"setTitle";
static NSString * webViewMessageNameSetActionInfo = @"setBtnInfo";
static NSString * webViewMessageNameSetBackActionInfo = @"setBackBtnInfo";
static NSString * webViewMessageNamePopView = @"popView";
static NSString * webViewMessageNameShowLoading = @"showLoading";
static NSString * webViewMessageNameDismissLoading = @"dismissLoading";
static NSString * webViewMessageNameShowToast = @"showToast";

static NSString * webViewMessageNameVersion = @"version"; // setVersion("1.0.1")
static NSString * webViewMessageNameLogout = @"logout";

static NSString * webViewMessageNameAppStorage = @"appStorage"; // (key) appStorageFetched(key, value)
static NSString * webViewMessageNameAppStorageDelete = @"appStorageDelete"; // (key)
static NSString * webViewMessageNameSetAppStorage = @"setAppStorage"; // (key, value) appStorageSet(bool)

@interface WebViewController ()

@property (strong, nonatomic) UIProgressView *progressView;

@property (copy, nonatomic) NSString *rightBarButtonEventJS;

@end

@implementation WebViewController

- (NSString *)baseURL {
//    return [AppConfiguration isProductionEnv] ? @"http://yyzbint.einwin.com/YYZB/HTML_CLIENT/pages/" : @"http://xtyyzb.einwin.com:83/YYZB/HTML_CLIENT/pages/";
    
    
//    return @"http://testyyzbhc.einwin.com/pages/";
    return @"http://yyzbhc.einwin.com/pages/";
    
}

- (WKWebView *)webView {
    if (!_webView) {
        NSString *source = [NSString stringWithFormat:@"localStorage.SessionKey = '%@';localStorage.UserId = '%@';localStorage.HelperSessionKey = '%@';localStorage.HelperId = '%@';", [UserInfoController sessionKey], [UserInfoController userID], [UserInfoController sessionKey], [UserInfoController userID]];
        WKWebViewConfiguration *config = WKWebViewConfiguration.new;
        WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        [config.userContentController addUserScript:script];
        [config.userContentController addScriptMessageHandler:self name:webViewMessageNameReload];
        [config.userContentController addScriptMessageHandler:self name:webViewMessageNameGetSessionInfo];
        [config.userContentController addScriptMessageHandler:self name:webViewMessageNamePushView];
        [config.userContentController addScriptMessageHandler:self name:webViewMessageNameSetTitle];
        [config.userContentController addScriptMessageHandler:self name:webViewMessageNameSetActionInfo];
        [config.userContentController addScriptMessageHandler:self name:webViewMessageNamePopView];
        [config.userContentController addScriptMessageHandler:self name:webViewMessageNameShowLoading];
        [config.userContentController addScriptMessageHandler:self name:webViewMessageNameDismissLoading];
        [config.userContentController addScriptMessageHandler:self name:webViewMessageNameShowToast];
        [config.userContentController addScriptMessageHandler:self name:webViewMessageNameVersion];
        [config.userContentController addScriptMessageHandler:self name:webViewMessageNameLogout];
        [config.userContentController addScriptMessageHandler:self name:webViewMessageNameSetBackActionInfo];
        [config.userContentController addScriptMessageHandler:self name:webViewMessageNameAppStorage];
        [config.userContentController addScriptMessageHandler:self name:webViewMessageNameAppStorageDelete];
        [config.userContentController addScriptMessageHandler:self name:webViewMessageNameSetAppStorage];
        
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
        _webView.backgroundColor = [ThemeColor lightGrayBGColor];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        _webView.scrollView.bounces = NO;
    }
    
    return _webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] init];
    backButtonItem.title = @"返回";
    self.navigationItem.backBarButtonItem = backButtonItem;
    [self.view addSubview:self.webView];
    self.webView.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:self.webView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0];
    NSLayoutConstraint *width = [NSLayoutConstraint constraintWithItem:self.webView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0];
    [self.view addConstraints:@[height, width]];
    
    self.progressView = UIProgressView.new;
    [self.view addSubview:self.progressView];
    self.progressView.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint *height0 = [NSLayoutConstraint constraintWithItem:self.progressView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:0.0 constant:0];
    NSLayoutConstraint *width0 = [NSLayoutConstraint constraintWithItem:self.progressView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0];
    [self.view addConstraints:@[height0, width0]];
    self.progressView.progress = 0.0;
    
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];

}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    [self loadPage];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.

    [self loadPage];
}
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    NSSet *websiteDataTypes
    = [NSSet setWithArray:@[
                            WKWebsiteDataTypeDiskCache,
                            //WKWebsiteDataTypeOfflineWebApplicationCache,
                            WKWebsiteDataTypeMemoryCache,
                            //WKWebsiteDataTypeLocalStorage,
                            //WKWebsiteDataTypeCookies,
                            //WKWebsiteDataTypeSessionStorage,
                            //WKWebsiteDataTypeIndexedDBDatabases,
                            //WKWebsiteDataTypeWebSQLDatabases
                            ]];
    //// All kinds of data
    //NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
    //// Date from
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    //// Execute
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        // Done
    }];
}
*/
#pragma mark - 

- (void)loadPage {
    if ([WebService isNetworkAvailable]) {
        if (self.HTMLURL.length) {
            NSString *URLString = @"";
            if (_linkType != nil) {
                if ([_linkType integerValue] ==1 || [_linkType integerValue]== 2) {
                    URLString = self.HTMLURL;
                }
            }else{
                
                if ([self.HTMLURL hasPrefix:@"../"]) {
                    
                    self.HTMLURL = [self.HTMLURL substringFromIndex:3];
                     URLString = [NSString stringWithFormat:@"%@%@", self.baseURL, self.HTMLURL];
                    
                }else if ([self.HTMLURL containsString:@"http://"]){
                    URLString = self.HTMLURL;

                } else {
                    URLString = [NSString stringWithFormat:@"%@%@", self.baseURL, self.HTMLURL];
                }
            }
            
                URLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                NSURLRequest * urlReuqest = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:URLString] cachePolicy:1 timeoutInterval:30.0f];
                [self.webView loadRequest:urlReuqest];
            }
        } else {
            NSURL *errorURL = [[NSBundle mainBundle] URLForResource:@"error" withExtension:@"html"];
            [self.webView loadFileURL:errorURL allowingReadAccessToURL:errorURL];
    }
    
}

#pragma mark -

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    NSLog(@"nnnaaammmmeee---%@",message.name);
    if ([message.name isEqualToString:webViewMessageNameReload]) {
        [self loadPage];
    }
    else if ([message.name isEqualToString:webViewMessageNameGetSessionInfo]) {
        NSString *js = [NSString stringWithFormat:@"sessionInfo('%@', '%@');", [UserInfoController sessionKey], [UserInfoController userID]];
        [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable r, NSError * _Nullable error) {
            [LoadingView showToast:r];
        }];
    }
    else if ([message.name isEqualToString:webViewMessageNamePushView]) {
        
        /*
         
         {
         
         "url": "地址",
         
         "title": "标题",
         
         "btndisplay": "是否显示按钮 0 不显示 1显示",
         
         "btntext": "按钮显示文字",
         
         "btnbg": "按钮背景",
         
         "btnevent": "对应的JS代码，string类型"
         
         }
         
         */
        id body = message.body;
        NSDictionary *bd;
        if ([body isKindOfClass:[NSDictionary class]]) {
            bd = body;
        } else if ([body isKindOfClass:[NSString class]]) {
            bd = [NSJSONSerialization JSONObjectWithData:[body dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
        }
        
        bd = [NSDictionaryNullKiller dataByReplacingNullWithEmptyString:bd];
        WebViewController *webViewController = [WebViewManager webViewController];
        webViewController.hidesBottomBarWhenPushed = YES;
        webViewController.HTMLURL = bd[@"url"];
        webViewController.title = bd[@"title"];
        if ([bd[@"btndisplay"] boolValue]) {
            webViewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:bd[@"btntext"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemTapped:)];
            self.rightBarButtonEventJS = bd[@"btnevent"];
        } else {
            self.rightBarButtonEventJS = nil;
        }
        [self.navigationController pushViewController:webViewController animated:YES];
    }
    else if ([message.name isEqualToString:webViewMessageNameSetTitle]) {
        self.title = message.body;
    }
    else if ([message.name isEqualToString:webViewMessageNameSetActionInfo]) {
        id body = message.body;
        NSDictionary *bd;
        if ([body isKindOfClass:[NSDictionary class]]) {
            bd = body;
        } else if ([body isKindOfClass:[NSString class]]) {
            bd = [NSJSONSerialization JSONObjectWithData:[body dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
        }
        bd = [NSDictionaryNullKiller dataByReplacingNullWithEmptyString:bd];
        if ([bd[@"btndisplay"] boolValue]) {
            if (bd[@"btntext"]) {
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:bd[@"btntext"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemTapped:)];
            } else if (bd[@"iconname"]) {
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:bd[@"iconname"]] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemTapped:)];
            }
            self.rightBarButtonEventJS = bd[@"btnevent"];
        } else {
            self.rightBarButtonEventJS = nil;
        }
    }
    else if ([message.name isEqualToString:webViewMessageNamePopView]) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else if ([message.name isEqualToString:webViewMessageNameShowLoading]) {
        [LoadingView show];
    }
    else if ([message.name isEqualToString:webViewMessageNameDismissLoading]) {
        [LoadingView dismiss];
    }
    else if ([message.name isEqualToString:webViewMessageNameShowToast]) {
        NSString *title = message.body;
        if ([title isKindOfClass:[NSString class]]) {
            [LoadingView showToast:title];
        }
    }
    else if ([message.name isEqualToString:webViewMessageNameVersion]) {
        NSDictionary *bundleInfo = [[NSBundle mainBundle] infoDictionary];
        [self.webView evaluateJavaScript:[NSString stringWithFormat:@"setVersion(\"%@\");", bundleInfo[@"CFBundleShortVersionString"]] completionHandler:nil];
    }
    else if ([message.name isEqualToString:webViewMessageNameLogout]) {
        [UserInfoController clearLoginInfo];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationNameUserLogout" object:nil];
    }
    else if ([message.name isEqualToString:webViewMessageNameSetBackActionInfo]) {
        self.navigationItem.hidesBackButton = YES;
        self.navigationItem.leftBarButtonItem = [self backButton];
    }
    else if ([message.name isEqualToString:webViewMessageNameAppStorage]) {
        NSString *key = message.body;
        if ([key isKindOfClass:[NSString class]] && key.length) {
            NSString *value = [[AppStorage sharedInstance] getObjectForKey:key];
            NSString *js = [NSString stringWithFormat:@"appStorageFetched(\"%@\", \"%@\");", key, value];
            [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable r, NSError * _Nullable error) {
                NSLog(@"%@", error);
            }];
        }
    }
    else if ([message.name isEqualToString:webViewMessageNameAppStorageDelete]) {
        NSString *key = message.body;
        if ([key isKindOfClass:[NSString class]] && key.length) {
            [[AppStorage sharedInstance] delObjectForKey:key];
        }
    }
    else if ([message.name isEqualToString:webViewMessageNameSetAppStorage]) {
        /*
         
         {
         
         "key": "地址",
         
         "value": "标题",
         
         }
         
         */
        id body = message.body;
        NSDictionary *bd;
        if ([body isKindOfClass:[NSDictionary class]]) {
            bd = body;
        } else if ([body isKindOfClass:[NSString class]]) {
            bd = [NSJSONSerialization JSONObjectWithData:[body dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
        }
        
        bd = [NSDictionaryNullKiller dataByReplacingNullWithEmptyString:bd];
        NSString *value;
        if ([bd[@"value"] isKindOfClass:[NSString class]]) {
            value = bd[@"value"];
        }
        NSString *key;
        if ([bd[@"key"] isKindOfClass:[NSString class]] && ((NSString *)bd[@"key"]).length) {
            key = bd[@"key"];
            [[AppStorage sharedInstance] setObject:value forKey:key];
            [self.webView evaluateJavaScript:[NSString stringWithFormat:@"appStorageSet(\"%@\", 1);", key] completionHandler:nil];
        }
    }
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
    }
}

- (void)rightBarButtonItemTapped:(UIBarButtonItem *)b {
    [self.webView evaluateJavaScript:self.rightBarButtonEventJS completionHandler:nil];
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    UIApplication *app = [UIApplication sharedApplication];
    NSURL *url = navigationAction.request.URL;
    if ([url.scheme isEqualToString:@"tel"]
        || [url.scheme isEqualToString:@"telprompt"]
        || [url.scheme isEqualToString:@"sms"]
        || [url.scheme isEqualToString:@"mailto"]
        ) {
        if ([app canOpenURL:url]) {
            [app openURL:url];
        } else {
            [LoadingView showToast:@"该设备不支持此功能"];
        }
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}


- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    self.progressView.progress = 0.0;
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    self.progressView.progress = 0.0;
}

- (UIBarButtonItem *)backButton {
    UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backButtonTapped)];
    return backButtonItem;
}

- (void)backButtonTapped {
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
